<template>
  <Card :bordered="false" dis-hover>
    <Button type="success" class="ivu-mb-16" @click="openModal"
      >线索导入</Button
    >
    <Table :columns="columns" :data="data" :loading="loading">
      <template slot="project" slot-scope="{ row }">
        {{ row.project_name.join(",") }}
      </template>
      <template slot="channel" slot-scope="{ row }">
        {{ row.channel_name
        }}<template v-if="row.second_channel_name"
          >/{{ row.second_channel_name }}</template
        >
      </template>
      <template slot="status" slot-scope="{ row }">
        <Tag v-if="row.status == -1">已删除</Tag>
        <Tag v-else color="success">成功</Tag>
      </template>
      <template slot="action" slot-scope="{ row }">
        <Button
          @click="handeldel(row)"
          v-if="row.status != -1"
          size="small"
          type="error"
          >删除</Button
        >
      </template>
    </Table>
    <Page
      :total="total"
      class="ivu-mt-16"
      v-model="params.page"
      :page-size="params.pageSize"
      @on-change="formSize"
      show-total
      show-elevator
      show-sizer
      @on-page-size-change="formChangePage"
    ></Page>
    <Modal v-model="showModal" title="线索导入" footer-hide>
      <Form
        :model="formItem"
        ref="formItem"
        :label-width="100"
        :rules="ruleInline"
      >
        <FormItem label="下载模板">
          <Button type="success" :to="downLoadUrl">下载模板</Button>
          <p>请安数据模板的格式准备要导入的数据</p>
        </FormItem>
        <FormItem label="上传文件" prop="file">
          <Upload
            :before-upload="checkimg"
            accept=".xls,.xlsx,.csv"
            :format="['xlsx', 'xls', 'csv']"
            action="/"
          >
            <Button type="success">上传文件</Button>
          </Upload>
          <div v-if="formItem.file !== null">{{ formItem.file.name }}</div>
        </FormItem>
        <FormItem label="来源渠道" prop="firstChannel">
          <Select
            v-model="formItem.firstChannel"
            required
            @on-change="changeFirst"
            label="一级渠道"
            style="width: auto"
          >
            <Option
              v-for="item in firstChannelList"
              :value="item.value"
              :key="item.value"
              >{{ item.label }}</Option
            >
          </Select>
          <Select
            v-model="formItem.secondChannel"
            v-if="formItem.firstChannel"
            clearable
            label="二级渠道"
            style="width: auto"
            class="ivu-ml-8"
          >
            <Option
              v-for="item in secondChannelList"
              :value="item.value"
              :key="item.value"
              >{{ item.label }}</Option
            >
          </Select>
        </FormItem>
      </Form>
      <div class="modalFoot">
        <Button @click="modalcancel()">取消</Button>
        <Button
          class="ivu-ml-16"
          :loading="modalloading"
          type="success"
          @click="modalSbmit()"
          >开始导入</Button
        >
      </div>
    </Modal>
  </Card>
</template>
<script>
import {
  marketingconsumegetsourcechannellist,
  clueList,
  clueImport,
  clueDel,
} from "@/api/hqapi";
import Setting from "@/setting";
import util from "@/libs/util";
export default {
  name: "clueimport",
  data() {
    const validateFile = (rule, value, callback) => {
      if (this.formItem.file !== null) callback();
      else callback(new Error("未选择任何文件"));
    };
    return {
      downLoadUrl: "",
      params: {
        page: 1,
        pageSize: 10,
      },
      total: 10,
      formItem: {
        firstChannel: "",
        secondChannel: "",
        file: null,
      },
      ruleInline: {
        firstChannel: [
          { required: true, message: "一级渠道不能为空", trigger: "change" },
        ],
        file: [{ validator: validateFile, required: true, trigger: "change" }],
      },
      showModal: false,
      modalloading: false,
      loading: false,
      columns: [
        {
          title: "项目名称",
          slot: "project",
          width: 120,
          tooltip: true,
        },
        {
          title: "导入数据条数",
          key: "total",
        },
        {
          title: "渠道",
          slot: "channel",
          width: 200,
        },
        // {
        //   title: "操作人",
        //   key: "realname",
        // },
        {
          title: "状态",
          slot: "status",
        },

        {
          title: "操作时间",
          key: "created_at",
          width: 180,
        },
        {
          title: "操作",
          slot: "action",
        },
      ],
      data: [],
      firstChannelList: [],
      secondChannelList: [],
    };
  },
  methods: {
    getData() {
      this.loading = true;
      clueList(this.params).then((res) => {
        this.total = res.total;
        this.data = res.list;
        this.loading = false;
      });
    },
    openModal() {
      this.formItem.firstChannel = "";
      this.formItem.secondChannel = "";
      this.formItem.file = null;
      this.showModal = true;
      this.$refs["formItem"].resetFields();
    },
    formChangePage(e) {
      this.params.pageSize = e;
      this.getData();
    },
    formSize(e) {
      this.params.page = e;
      this.getData();
    },
    checkimg(e) {
      for (let item of this.$refs.formItem.fields) {
        if (item.prop == "file") {
          item.resetField();
        }
      }
      this.formItem.file = e;
      return false;
    },
    changeFirst(e) {
      this.firstChannelList.forEach((item) => {
        if (this.formItem.firstChannel == item.value) {
          this.secondChannelList = item.children;
        }
      });
    },
    handeldel(e) {
      this.$Modal.confirm({
        title: "温馨提示",
        content: "确定删除此项?",
        onOk: () => {
          clueDel({ id: e.id }).then((res) => {
            this.$Message.warning("删除成功！");
            this.getData();
          });
        },
      });
    },
    modalcancel() {
      this.showModal = false;
    },
    modalSbmit() {
      this.$refs["formItem"].validate((valid) => {
        if (valid) {
          let FormDatas = new FormData();
          FormDatas.append("file", this.formItem.file);
          FormDatas.append("channel_id", this.formItem.firstChannel);
          if (this.formItem.secondChannel) {
            FormDatas.append("second_channel_id", this.formItem.secondChannel);
          }

          this.modalloading = true;
          clueImport(FormDatas)
            .then((res) => {
              this.$Message.warning("上传成功！");
              this.modalloading = false;
              this.showModal = false;
              this.getData();
            })
            .catch(() => {
              this.modalloading = false;
            });
        }
      });
    },
  },
  mounted() {
    let date = new Date();
    let t = date.getTime();
    this.downLoadUrl =
      Setting.apiBaseURL +
      `/excel/clue/clue_data.xls?auth_access_token=${util.cookies.get(
        "token"
      )}&t=${t}`;
    this.getData();
    marketingconsumegetsourcechannellist().then((res) => {
      this.firstChannelList = res;
    });
  },
};
</script>
<style lang="less" scoped>
.modalFoot {
  text-align: right;
  border-top: 1px solid #ddd;
  padding-top: 16px;
  margin-top: 24px;
}
</style>
